﻿using gAMS_Sacombank.CommonClass;
using gAMS_Sacombank.Resources;
using gAMS_Sacombank.ViewModels.Common;
using GalaSoft.MvvmLight.Messaging;
using mvvmCommon;
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using gAMS_Sacombank.AssetService;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace gAMS_Sacombank.ViewModels.AssCommon
{
    public class SupplierEditViewModel : ViewModelBase
    {
        private SupplierClient supplierClient;
        private RegionsClient regionClient;
        private SupplierTypeClient suppliertypeClient;
        public SupplierEditViewModel()
        {
            this.actionCommand = new ActionButton(this);
            this.messagePop = new MessageAlarmViewModel();
            Messenger.Default.Register<ChildMessage>(this, CurrencyEditSendMessageRecieve);

            this.Load();
            this.IsChecked = "True";
        }

        private void CurrencyEditSendMessageRecieve(ChildMessage obj)
        {

            if (obj.action.Equals(ActionMenuButton.View))
            {
                ActionMenuButton.actionControl.SetAllAction(null, null, null, null, null, null, null);
                this.HeaderText = CommonResource.lblApprove;
                this.IsView = false;
            }
            else
            {
                ActionMenuButton.actionControl.SetAllAction(null, actionCommand, null, null, null);
                this.isEdit = obj.isEdit;
                this.HeaderText = this.isEdit ? CommonResource.lblEdit : CommonResource.lblInsert;
                this.IsView = true;
            }

            this.messagePop.Reset();
            this.CurrentItem = obj.currentObject != null ? (obj.currentObject as CM_SUPPLIER)
                : new CM_SUPPLIER()
                {
                    MAKER_ID = CurrentSystemLogin.CurrentUser.TLNANME,
                    SUP_ID = "",
                    SUP_NAME = "",
                    SUP_TYPE_ID = "",
                   // BRANCHCODE = "",
                    REGION_ID = "",
                    TEL = "",
                    ADDR = "",
                    NOTES = "",
                    AUTH_STATUS = CurrentSystemLogin.IsAppFunction ? "U" : "A",
                    RECORD_STATUS = "1",
                    //FATHER_ID = ""
                };

            if (!obj.action.Equals(ActionMenuButton.Insert))
                //this.();

            this.IsChecked = this.currentItem.RECORD_STATUS.Equals("1") ? "True" : "False";
            if (this.currentItem.AUTH_STATUS.Equals("A") && CurrentSystemLogin.IsAppFunction)
                this.IsApproved = Visibility.Visible.ToString();
            else
                this.IsApproved = Visibility.Collapsed.ToString();

            this.OnPropertyChanged("IsView");
            this.OnPropertyChanged("IsApproved");
            this.OnPropertyChanged("IsChecked");
            this.OnPropertyChanged("");
        }

        private string preStatus;//Gia tri AUTH_STATUS truoc khi duyet, cap nhat

        #region[All Properties]

        public bool IsView { get; set; }

        //Tinh trang record co dang hoat trong hay khong
        public string IsChecked { get; set; }

        public string IsApproved { get; set; }
        //Message Alarm validate
        private MessageAlarmViewModel messagePop;
        public MessageAlarmViewModel MessagePop
        {
            get
            {
                return this.messagePop;
            }

            set
            {
                this.messagePop = value;
                this.OnPropertyChanged("MessagePop");
            }
        }
        // function insert or edit
        private bool isEdit;
        public string IsEnable
        {
            get
            {
                return (!this.isEdit).ToString();
            }
        }

        //Action Button Property    
        private ICommand actionCommand;
        public ICommand ActionCommand
        {
            get
            {
                return this.actionCommand;
            }

            set
            {
                this.actionCommand = value;
                this.OnPropertyChanged("ActionCommand");
            }
        }

        //Current Items edit
        private CM_SUPPLIER currentItem;
        public CM_SUPPLIER CurrentItem
        {
            get
            {
                return this.currentItem;
            }

            set
            {
                this.currentItem = value;
                this.OnPropertyChanged("CurrentItem");
            }
        }

        //set header title
        private string headerText;
        public string HeaderText
        {
            get
            {
                return this.headerText;
            }

            set
            {
                this.headerText = value;
                this.OnPropertyChanged("HeaderText");
            }
        }

     
        public ObservableCollection<CM_REGION> RegionData { get; set; }
       
        public string RegionID
        {
            get
            {
                return this.currentItem.REGION_ID;
            }

            set
            {
                this.currentItem.REGION_ID = value;
                this.OnPropertyChanged("RegionID");
                //this.LoadSupplierTypeParent();
            }
        }
        public ObservableCollection<CM_SUPPLIERTYPE> SupplierTypeData { get; set; }
        public string SupTypeID
        {
            get
            {
                return this.currentItem.SUP_TYPE_ID;
            }

            set
            {
                this.currentItem.SUP_TYPE_ID = value;
                this.OnPropertyChanged("SupTypeID");
                //this.LoadSupplierTypeParent();
            }
        }

        public ObservableCollection<CM_SUPPLIER> SupplierData { get; set; }

        #endregion

        #region[Action Functions]

        private void OkAction()
        {
            RefreshValidator();
            if (!this.messagePop.HasError())
            {
                this.currentItem.RECORD_STATUS = this.IsChecked.Equals("True") ? "1" : "0";
                if (this.isEdit)
                {
                    this.preStatus = this.currentItem.AUTH_STATUS;
                    MyHelper.IsBusy();
                    this.supplierClient.UpdateSupplierAsync(this.currentItem);
                }
                else
                {
                    this.currentItem.CREATE_DT = DateTime.Now;
                    MyHelper.IsBusy();
                    this.supplierClient.InsertSupplierAsync(this.currentItem);
                }
            }
        }

        private void CancelAction()
        {
            Messenger.Default.Send(new ParentMessage() { currentObject = null });
        }

        private void Approve()
        {
            this.messagePop.Reset();
            if (this.currentItem.AUTH_STATUS.Equals("A")) return;
            if (this.currentItem.MAKER_ID.Equals(CurrentSystemLogin.CurrentUser.TLNANME))
            {
                this.messagePop.SetSingleError(ValidatorResource.lblErrorPermission);
                return;
            }
            this.currentItem.CHECKER_ID = CurrentSystemLogin.CurrentUser.TLNANME;
            this.currentItem.APPROVE_DT = CurrentSystemInfor.CurrentDate;
            MyHelper.IsBusy();
            this.supplierClient.ApproveSupplierAsync(this.currentItem);
        }
        private void RefreshValidator()
        {
            this.messagePop.Reset();
            string notEmpty = " " + ValidatorResource.NotEmpty;
            if (this.currentItem.SUP_CODE == null || this.currentItem.SUP_CODE.Equals(""))
                this.messagePop.SetError(AssCommonResource.Sup_Code + notEmpty);
            if (this.currentItem.SUP_NAME.Equals(""))
                this.messagePop.SetError(AssCommonResource.SupName + notEmpty);
            if (this.currentItem.REGION_ID == null || this.currentItem.REGION_ID.Equals(""))
                this.messagePop.SetError(AssCommonResource.RegionID + notEmpty);
            if (this.currentItem.SUP_TYPE_ID == null || this.currentItem.SUP_TYPE_ID.Equals(""))
                this.messagePop.SetError(AssCommonResource.SupTypeName + notEmpty);

           //if (!this.currentItem.TEL.Equals("") || this.currentItem.TEL.Length < 7)
           //     this.messagePop.SetError(AssCommonResource.Tel + " " + ValidatorResource.lblNotTrue);
            //if (this.currentItem.SUPTYPEID != null && !this.currentItem.SUPTYPEID.Equals("HS") )
            //    this.messagePop.SetError(AssCommonResource.FatherID + notEmpty);
        }
        private void Load()
        {
            try
            {
                this.supplierClient = new SupplierClient();
                this.regionClient = new RegionsClient();
                this.suppliertypeClient = new SupplierTypeClient();

                this.supplierClient.UpdateSupplierCompleted += new EventHandler<UpdateSupplierCompletedEventArgs>(updateCompleted);
                this.supplierClient.InsertSupplierCompleted += new EventHandler<InsertSupplierCompletedEventArgs>(insetCompleted);
                this.supplierClient.ApproveSupplierCompleted += new EventHandler<ApproveSupplierCompletedEventArgs>(approveCompleted);
                this.supplierClient.GetByTopSupplierCompleted += new EventHandler<GetByTopSupplierCompletedEventArgs>(getSupplierCompleted);

                this.regionClient.GetByTopRegionAsync("", " RECORD_STATUS = '1' ", "");
                this.regionClient.GetByTopRegionCompleted += (s, e) =>
                {
                    try
                    {
                        if (e.Result != null)
                            this.RegionData = e.Result;
                        else
                            this.RegionData = new ObservableCollection<CM_REGION>();
                        this.OnPropertyChanged("RegionData");
                    }
                    catch (Exception)
                    {
                    }
                };
                this.suppliertypeClient.GetByTopSupplierTypeAsync("","", "");
                this.suppliertypeClient.GetByTopSupplierTypeCompleted += (s, e) =>
                {
                    try
                    {
                        if (e.Result != null)
                            this.SupplierTypeData = e.Result;
                        else
                            this.SupplierTypeData = new ObservableCollection<CM_SUPPLIERTYPE>();
                        this.OnPropertyChanged("SupplierTypeData");
                    }
                    catch (Exception)
                    {
                    }
                };
              
            }
            catch (Exception)
            {
                this.messagePop.SetSingleError(CommonResource.errorCannotConnectServer);
            }
        }

        private void getSupplierCompleted(object sender, GetByTopSupplierCompletedEventArgs e)
        {
            try
            {
                if (e.Result != null && e.Result.Count > 0)
                    this.SupplierData = e.Result;
                else
                    this.SupplierData = new ObservableCollection<CM_SUPPLIER>();

                this.OnPropertyChanged("SupplierData");
                this.OnPropertyChanged("CurrentItem");
            }
            catch (Exception)
            {
                this.messagePop.SetSingleError(CommonResource.errorCannotConnectServer);
            }
        }

        private void updateCompleted(object sender, UpdateSupplierCompletedEventArgs e)
        {
            try
            {
                if (e.Result.Equals(ListMessage.True))
                {
                    this.IsApproved = Visibility.Collapsed.ToString();
                    this.OnPropertyChanged("IsApproved");
                    this.messagePop.Successful(ValidatorResource.UpdateSuccessful);
                }
                else
                {
                    this.currentItem.AUTH_STATUS = this.preStatus;
                    if (ListMessage.Message.ContainsKey(e.Result))
                        this.messagePop.SetSingleError(ValidatorResource.ErrorUpdate + "\n " + ListMessage.Message[e.Result]);
                    else
                        this.messagePop.SetSingleError(ValidatorResource.ErrorUpdate + "\n " + e.Result);
                }
            }
            catch (Exception)
            {
                this.messagePop.SetSingleError(CommonResource.errorCannotConnectServer);
            }
            finally
            {
                MyHelper.IsFree();
            }
        }

        private void insetCompleted(object sender, InsertSupplierCompletedEventArgs e)
        {
            try
            {
                if (e.Result.Equals(ListMessage.True))
                {
                    this.messagePop.Successful(ValidatorResource.InsertSuccessful);
                    Messenger.Default.Send(new ParentMessage() { isEdit = this.isEdit, currentObject = this.currentItem });
                }
                else
                {
                    if (ListMessage.Message.ContainsKey(e.Result))
                        this.messagePop.SetSingleError(ValidatorResource.ErrorInsert + "\n " + ListMessage.Message[e.Result]);
                    else
                        this.messagePop.SetSingleError(ValidatorResource.ErrorInsert + "\n " + e.Result);
                }
            }
            catch (Exception)
            {
                this.messagePop.SetSingleError(CommonResource.errorCannotConnectServer);
            }
            finally
            {
                MyHelper.IsFree();
            }
        }

        private void approveCompleted(object sender, ApproveSupplierCompletedEventArgs e)
        {
            try
            {
                if (e.Result.Equals(ListMessage.True))
                {
                    this.currentItem.AUTH_STATUS = "A";
                    this.IsApproved = Visibility.Visible.ToString();
                    this.OnPropertyChanged("IsApproved");
                    this.messagePop.Successful(ValidatorResource.SuccessfulApprove);
                }
                else
                {
                    if (ListMessage.Message.ContainsKey(e.Result))
                        this.messagePop.SetSingleError(ValidatorResource.ErrorApprove + "\n " + ListMessage.Message[e.Result]);
                    else
                        this.messagePop.SetSingleError(ValidatorResource.ErrorApprove + "\n " + e.Result);
                }
            }
            catch (Exception)
            {
                this.messagePop.SetSingleError(CommonResource.errorCannotConnectServer);
            }
            finally
            {
                MyHelper.IsFree();
            }
        }
        #endregion
        //Command button action
        public class ActionButton : ICommand
        {

            private SupplierEditViewModel viewModel;
            public ActionButton(SupplierEditViewModel viewModel)
            {
                this.viewModel = viewModel;
                this.viewModel.PropertyChanged += (s, e) =>
                {
                    if (this.CanExecuteChanged != null)
                    {
                        this.CanExecuteChanged(this, new EventArgs());
                    }
                };
            }

            public bool CanExecute(object parameter)
            {
                return true;
            }

            public event EventHandler CanExecuteChanged;

            public void Execute(object parameter)
            {
                switch (parameter.ToString())
                {
                    case "Cancel": this.viewModel.CancelAction(); break;
                    case ActionMenuButton.Update: this.viewModel.OkAction(); break;
                    case ActionMenuButton.Approve: this.viewModel.Approve(); break;
                    default: break;
                }

            }
        }
    }
}
